package org.kernely.security.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.kernely.persistence.service.SessionService;
import org.kernely.security.persistence.Group;
import org.osgi.service.component.ComponentContext;

public class GroupDAO {
	/**
	 * SessionService service
	 */
	private static SessionService service;
	
	/**
	 * The group dao instance
	 */
	private static GroupDAO instance;

	/**
	 * Store the group dao instance 
	 * @return the group dao
	 */
	public static GroupDAO getInstance() {
		return instance;
	}
	
	/**
	 * Set the persistence session service
	 * @param sessionService the session service to set
	 */
	public final void setPersistenceService(SessionService sessionService) {
		service = sessionService;
	}

	/**
	 * Activate the component, called by SC runtime
	 * @param ctxt the activation context
	 */
	protected final void activate(ComponentContext ctxt) {
		instance = this;
	}
	
	/**
	 * Gets the session service.
	 * 
	 * @return the session service
	 */
	public static SessionService getService() {
		return service;
	}

	/**
	 * Sets the session service.
	 * 
	 * @param service
	 *            the session service to set
	 */
	public static void setService(SessionService service) {
		GroupDAO.service = service;
	}
	
	/**
	 * Returns all the groups stored
	 * @return a list of all groups stored
	 */
	public final List<Group> getAllGroups(){
		Session session = service.getSession();
		return (List<Group>) session.createCriteria(Group.class).list();
	}

	/**
	 * Returns the group which have the group_id
	 * @param groupId : the group's ID
	 * @return : the group which have group_id
	 */
	public final Group getGroupById(int groupId){
		Session session = service.getSession();
		Criteria crit = session.createCriteria(Group.class);
		crit.add(Restrictions.like("id", groupId));
		return (Group) crit.list().get(0);
	}
	
	/**
	 * Returns the group which have the name name
	 * @param name : the name of the group needed
	 * @return the group which have the name name
	 */
	public final Group findGroupByName(String name){
		Session session = service.getSession();
		Criteria crit = session.createCriteria(Group.class);
		crit.add(Restrictions.like("name", name));
		return (Group) crit.list().get(0);
	}
	
	/**
	 * Persists a new Group
	 * @param g : the new group
	 */
	public final void saveGroup(Group g){
		Session session = service.getSession();
		session.save(g);
	}
	
	/**
	 * Update an existing group
	 * @param g : the group to update
	 */
	public final void updateGroup(Group g){
		Session session = service.getSession();
		session.merge(g);
	}
	
	/**
	 * Delete an existing group
	 * @param g : the group to delete
	 */
	public final void deleteGroup(Group g){
		Session session = service.getSession();
		session.delete(g);
	}
}
